package com.cloud.log.autolevel.config;

import com.cloud.log.autolevel.bean.properites.ZkConfigProperties;
import com.cloud.log.autolevel.manager.ZkManager;
import com.cloud.log.autolevel.service.LogLevelSettingService;
import com.cloud.log.autolevel.service.ConfigChangeService;
import com.cloud.log.autolevel.service.impl.ZkConfigChangeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: ZhangKaiQiang
 * @date: 2021/7/18
 * @time: 16:28
 **/
@Configuration
@ConditionalOnProperty(prefix = "auto.level.zk", name = "enable", havingValue = "true")
@EnableConfigurationProperties(ZkConfigProperties.class)
public class ZkManagerConfig {

    private final ZkConfigProperties zkConfigProperties;

    private final LogLevelSettingService logLevelSettingService;

    @Autowired
    public ZkManagerConfig(
            ZkConfigProperties zkConfigProperties,
            LogLevelSettingService logLevelSettingService) {
        this.zkConfigProperties = zkConfigProperties;
        this.logLevelSettingService = logLevelSettingService;
    }

    @Bean
    public ZkManager zkManager() {
        return new ZkManager(
                zkConfigProperties.getConnectionUrl(),
                zkConfigProperties.getSessionTimeOutMs(),
                zkConfigProperties.getConnectionTimeoutMs(),
                zkConfigProperties.getNamespace());
    }

    @Bean
    public ConfigChangeService zkConfigChangeService() {
        ZkManager zkManager = this.zkManager();
        return new ZkConfigChangeServiceImpl(zkManager,logLevelSettingService);
    }
}